package com.sky.service.impl;

import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        log.info("日期集合：{}", dateList);

        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(localDate -> {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);

            Double turnover = orderMapper.getByMap(map); // 当日营业总额


            turnover = turnover == null ? 0.0 : turnover;
            log.info("当日营业额：{}", turnover);
            turnoverList.add(turnover);
        });



        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();


        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> totalUserList = new ArrayList<>(); // 总用户
        List<Integer> newUserList = new ArrayList<>(); // 每日新增用户

        dateList.forEach(localDate -> {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer totalUser = orderMapper.userStatistics(null, endTime);
            totalUserList.add(totalUser);

            Integer newUser = orderMapper.userStatistics(beginTime, endTime);
            newUserList.add(newUser);


        });

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ",")).build();

        return userReportVO;
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList  = new ArrayList<>(); // 每日订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>(); // 每日有效订单总数集合



        dateList.forEach(localDate -> {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer orderCount = orderMapper.getOrderCount(beginTime, endTime, null);
            orderCountList.add(orderCount);

            Integer validOrderCount = orderMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);


        });

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get(); // 订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get(); // 有效订单总数

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue(); // 每日订单完成率

        }


        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();

        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTmie = LocalDateTime.of(end, LocalTime.MAX);

            List<OrderDetail> orderDetails = orderMapper.getTop(beginTime, endTmie);

            List<String> names = orderDetails.stream().map(OrderDetail::getName).collect(Collectors.toList());
            log.info("names: {}", names);
            List<Integer> numbers = orderDetails.stream().map(OrderDetail::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ",")).build();


        return salesTop10ReportVO;
    }

    /**
     * 数据导出
     * @param response
     */
    @Override
    public void load(HttpServletResponse response) {
        LocalDate beginday = LocalDate.now().minusDays(30); // 前第30天
        LocalDate endday = LocalDate.now().minusDays(1); // 昨天

        LocalDateTime beginTime = LocalDateTime.of(beginday, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endday, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime); // 获得近30天总数据、

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("temper/运营数据报表模板.xlsx"); // 通过类加载器获得模板的输入流

        try {

            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);

            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginTime + "--" + endTime );

            XSSFRow sheetRow4 = sheet.getRow(3);
            sheetRow4.getCell(2).setCellValue(businessData.getTurnover());
            sheetRow4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheetRow4.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow sheetRow5 = sheet.getRow(4);
            sheetRow5.getCell(2).setCellValue(businessData.getValidOrderCount());
            sheetRow5.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = beginday.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO BusinessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(BusinessDataVO.getTurnover());
                row.getCell(3).setCellValue(BusinessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(BusinessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(BusinessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(BusinessDataVO.getNewUsers());
            }

            ServletOutputStream out = response.getOutputStream(); // 获得输出流
            excel.write(out);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
